import { pinia } from '@/store'
import { cloneDeep } from '@/utils'
import { useAuthStore } from './auth'

export const useMenuStore = defineStore('menu', () => {
	// 主菜单
	const listMenu = ref<MenuType.Menu[]>([])
	// 上次更新主菜单
	const lastBuildMenuTime = ref<number>(0)
	// 记录构建主菜单时间
	const setLastBuildMenuTime = () => {
		lastBuildMenuTime.value = new Date().getTime()
	}
	// 赋值主菜单
	const setListMenu = (list: MenuType.Menu[]) => {
		listMenu.value = list
		list?.length > 0 && setLastBuildMenuTime()
	}
	// 重置菜单
	const resetMenu = (): void => {
		listMenu.value = []
		lastBuildMenuTime.value = 0
	}

	// 生成菜单
	const buildMenuAction = async () => {
		const { routeList } = useAuthStore()
		const data = filterMenuFun(cloneDeep(routeList) as MenuType.Menu[])
		setListMenu(data)
	}
	// 处理目录隐藏属性：hideMenu
	const filterMenuFun = (list: MenuType.Menu[]): MenuType.Menu[] => {
		return list
			.filter((item: MenuType.Menu) => !item.meta?.hideMenu)
			.map((item: MenuType.Menu) => {
				if (item.children) item.children = filterMenuFun(item.children)
				return item
			})
	}

	// 渲染主菜单数据
	const mainMenu = ref<LayoutType.LayoutMenuMode>({
		list: [],
		visible: false,
		defaultActive: ''
	})
	// 渲染分割菜单数据
	const splitMenu = ref<LayoutType.LayoutMenuMode>({
		list: [],
		visible: false,
		defaultActive: ''
	})
	// 重置渲染主菜单数据
	const resetMainMenu = (): void => {
		mainMenu.value = {
			list: [],
			visible: false,
			defaultActive: ''
		}
	}
	// 重置渲染分割菜单数据
	const resetSplitMenu = (): void => {
		splitMenu.value = {
			list: [],
			visible: false,
			defaultActive: ''
		}
	}
	return {
		listMenu,
		lastBuildMenuTime,
		mainMenu,
		splitMenu,
		resetMainMenu,
		resetSplitMenu,
		setListMenu,
		resetMenu,
		buildMenuAction
	}
})
// 在组合式setup之外使用
export function useMenuStoreWithout() {
	return useMenuStore(pinia)
}
